<template>
  <div class="department-tree">
    <el-card shadow="never">
      <template #header>
        <div class="tree-header">
          <span>公司组织结构</span>
          <el-button type="primary" link @click="handleExpandAll">
            {{ isExpandAll ? '收起全部' : '展开全部' }}
          </el-button>
        </div>
      </template>
      <el-tree
        ref="treeRef"
        :data="departmentData"
        node-key="id"
        highlight-current
        :props="defaultProps"
        :expand-on-click-node="false"
        :default-expanded-keys="expandedKeys"
        @node-click="handleNodeClick"
      >
        <template #default="{ node }">
          <span class="custom-tree-node">
            <el-icon>
              <OfficeBuilding />
            </el-icon>
            <span>{{ node.label }}</span>
            <span class="employee-count" v-if="node.data?.count">({{ node.data.count }})</span>
          </span>
        </template>
      </el-tree>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { OfficeBuilding } from '@element-plus/icons-vue'

const props = defineProps({
  departmentData: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['node-click'])

const defaultProps = {
  children: 'children',
  label: 'label'
}

const treeRef = ref()
const isExpandAll = ref(false)
const expandedKeys = ref([1, 2, 3]) // 默认展开的节点ID

// 展开/收起全部
const handleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value
  const nodes = props.departmentData.map(item => item.id)
  nodes.forEach(id => {
    treeRef.value.store.nodesMap[id].expanded = isExpandAll.value
  })
}

// 部门节点点击事件
const handleNodeClick = (data) => {
  emit('node-click', data)
}

// 暴露方法给父组件
defineExpose({
  setCurrentKey: (key) => {
    treeRef.value?.setCurrentKey(key)
  }
})
</script>

<style lang="less" scoped>
.department-tree {
  width: 280px;
  flex-shrink: 0; // 防止树组件被压缩
  margin-right: 0; // 移除右边距，因为已经在content中添加了左边距
  height: 100%;

  :deep(.el-card) {
    height: 100%;
    display: flex;
    flex-direction: column;

    .el-card__body {
      flex: 1;
      overflow: auto; // 树内容超出时滚动
      padding: 10px;
    }
  }

  .tree-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    font-size: 14px;

    .el-icon {
      margin-right: 8px;
      color: #409eff;
    }

    .employee-count {
      margin-left: 8px;
      color: #909399;
      font-size: 12px;
    }
  }
}
</style>